<template>
  <a-modal
    width="720px"
    :bodyStyle="store.userStore.bodyStyle"
    v-model:open="modal.open"
    :title="modal.title"
    ok-text="确认"
    :maskClosable="false"
  >
    <div class="modal-content" style="min-height: 400px">
      <a-form class="modelForm" ref="modelForm" :model="showCondition">
        <a-form-item>
          <div class="row">
            <div>
              当满足以下
              <a-select style="width: 80px" v-model:value="showCondition.operator">
                <a-select-option value="AND">全部</a-select-option>
                <a-select-option value="OR">任意</a-select-option>
              </a-select>
              条件时，
              <a-select style="width: 80px" v-model:value="showCondition.show">
                <a-select-option :value="true">显示</a-select-option>
                <a-select-option :value="false">隐藏</a-select-option>
              </a-select>
              此题目
            </div>
            <div>
              <a-checkbox v-model:checked="simpleCheck">保存时简化条件</a-checkbox>
            </div>
          </div>
        </a-form-item>
        <a-tree
          :tree-data="showCondition.conditions"
          showLine
          :expandedKeys="expandedKeys"
          :expandAction="false"
          :selectable="false"
          :fieldNames="{ children: 'conditions' }"
        >
          <template #title="{ data: c }">
            <a-row :gutter="8">
              <a-col>
                <a-dropdown>
                  <template #overlay>
                    <a-menu @click="handleMenuClick($event, c)">
                      <a-menu-item key="AND"> AND </a-menu-item>
                      <a-menu-item key="OR"> OR </a-menu-item>
                      <a-menu-item key="==="> 条件 </a-menu-item>
                    </a-menu>
                  </template>
                  <a-button>
                    <template v-if="c.operator === 'AND'"> AND </template>
                    <template v-else-if="c.operator === 'OR'"> OR </template>
                    <template v-else>条件</template>
                    <icon-font type="DownOutlined" />
                  </a-button>
                </a-dropdown>
              </a-col>
              <template v-if="['AND', 'OR'].includes(c.operator)">
                <a-col class="ft">
                  <icon-font
                    v-if="c.names[c.names.length - 1]"
                    class="icon-del"
                    type="icon-shanchu"
                    @click="conditionsDel(c.names[c.names.length - 1], c.names)"
                  />
                  <icon-font
                    v-else
                    class="icon-plus"
                    type="icon-xinzeng"
                    @click="conditionsAdd(c.names)"
                  />
                </a-col>
              </template>
              <template v-else>
                <a-col>
                  <a-form-item
                    :name="[...c.names, 'id']"
                    :rules="{
                      required: true,
                      message: '关联题目不能为空',
                      trigger: 'change',
                      whitespace: true
                    }"
                  >
                    <a-select
                      style="width: 200px"
                      v-model:value="c.id"
                      @change="conditionsChange(props.showConditionObj[c.id].type, c)"
                      placeholder="关联问题"
                    >
                      <a-select-option value="custom"> 自定义校验 </a-select-option>
                      <a-select-opt-group
                        v-for="module in props.formData?.content"
                        :key="module.id"
                      >
                        <template #label>
                          <span>
                            {{ module.name }}
                          </span>
                        </template>
                        <a-select-option
                          v-for="item in module.list"
                          :key="item.id"
                          :value="item.id"
                          >{{ item.name }}</a-select-option
                        >
                      </a-select-opt-group>
                    </a-select>
                  </a-form-item>
                </a-col>
                <template v-if="c.id">
                  <template v-if="props.showConditionObj[c.id].type === '自定义规则'">
                    <a-col class="form-item" :span="10">
                      <a-form-item
                        v-if="c.operator !== '填写完成'"
                        label="规则"
                        :name="[...c.names, 'value']"
                        :rules="{
                          required: true,
                          message: '自定义规则不能为空',
                          trigger: 'change',
                          whitespace: true
                        }"
                      >
                        <a-input
                          style="width: 100%"
                          v-model:value="c.value"
                          autocomplete="off"
                          placeholder="自定义规则"
                        />
                      </a-form-item>
                    </a-col>
                  </template>
                  <template v-else-if="props.showConditionObj[c.id].type === '输入'">
                    <a-col class="form-item" :span="4">
                      <a-select
                        style="width: 100px"
                        v-model:value="c.operator"
                        @change="operatorChange($event, c)"
                        placeholder="选项"
                      >
                        <a-select-option value="填写完成">填写完成</a-select-option>
                        <a-select-option value="===">{{ '=' }}</a-select-option>
                        <a-select-option value=">">{{ '>' }}</a-select-option>
                        <a-select-option value=">=">{{ '≥' }}</a-select-option>
                        <a-select-option value="<">{{ '<' }}</a-select-option>
                        <a-select-option value="<=">{{ '≤' }}</a-select-option>
                        <a-select-option value="!==">{{ '≠' }}</a-select-option>
                      </a-select>
                    </a-col>
                    <a-col class="form-item" :span="6">
                      <a-form-item
                        v-if="c.operator !== '填写完成'"
                        label="填写"
                        :name="[...c.names, 'value']"
                        :rules="{
                          required: true,
                          message: '填写内容不能为空',
                          trigger: 'change',
                          whitespace: true
                        }"
                      >
                        <a-input
                          style="width: 120px"
                          v-model:value="c.value"
                          autocomplete="off"
                          placeholder="填写内容"
                        />
                      </a-form-item>
                    </a-col>
                  </template>
                  <template v-else-if="props.showConditionObj[c.id].type === '数字选择'">
                    <a-col class="form-item" :span="4">
                      <a-select
                        style="width: 100px"
                        v-model:value="c.operator"
                        @change="operatorChange($event, c)"
                        placeholder="选项"
                      >
                        <a-select-option value="填写完成">填写完成</a-select-option>
                        <a-select-option value="===">{{ '=' }}</a-select-option>
                        <a-select-option value=">">{{ '>' }}</a-select-option>
                        <a-select-option value=">=">{{ '≥' }}</a-select-option>
                        <a-select-option value="<">{{ '<' }}</a-select-option>
                        <a-select-option value="<=">{{ '≤' }}</a-select-option>
                        <a-select-option value="!==">{{ '≠' }}</a-select-option>
                      </a-select>
                    </a-col>
                    <a-col class="form-item" :span="6">
                      <a-form-item
                        label="选择"
                        v-if="c.operator !== '填写完成'"
                        :name="[...c.names, 'value']"
                        :rules="{
                          required: true,
                          message: '选择项不能为空',
                          trigger: 'change'
                        }"
                      >
                        <a-select style="width: 160px" v-model:value="c.value" placeholder="选项">
                          <a-select-option
                            v-for="tag in props.showConditionObj[c.id].config.max -
                            props.showConditionObj[c.id].config.min"
                            :key="tag"
                            :value="props.showConditionObj[c.id].config.min + tag - 1"
                            >{{
                              props.showConditionObj[c.id].config.min + tag - 1
                            }}</a-select-option
                          >
                        </a-select>
                      </a-form-item>
                    </a-col>
                  </template>
                  <a-col
                    class="form-item"
                    :span="10"
                    v-else-if="
                      ['单选', '单选+输入', '多选', '多选+输入'].includes(
                        props.showConditionObj[c.id].type
                      )
                    "
                  >
                    <a-form-item
                      label="选择"
                      :name="[...c.names, 'value']"
                      :rules="{
                        required: true,
                        message: '选择项不能为空',
                        trigger: 'change'
                      }"
                    >
                      <a-select style="width: 160px" v-model:value="c.value" placeholder="选项">
                        <a-select-option
                          v-for="item in props.showConditionObj[c.id].options"
                          :key="item.sort"
                          :value="item.sort"
                          >{{ item.sort + '.' + item.label }}</a-select-option
                        >
                      </a-select>
                    </a-form-item>
                  </a-col>
                  <a-col v-else :span="10" style="line-height: 32px">
                    <a-select
                      style="width: 100px"
                      v-model:value="c.operator"
                      @change="operatorChange($event, c)"
                      placeholder="选项"
                    >
                      <a-select-option value="填写完成">填写完成</a-select-option>
                    </a-select>
                  </a-col>
                </template>
                <a-col v-else :span="10" />
                <a-col class="ft">
                  <icon-font
                    v-if="c.names[c.names.length - 1]"
                    class="icon-del"
                    type="icon-shanchu"
                    @click="conditionsDel(c.names[c.names.length - 1], c.names)"
                  />
                  <icon-font
                    v-else
                    class="icon-plus"
                    type="icon-xinzeng"
                    @click="conditionsAdd(c.names)"
                  />
                </a-col>
              </template>
            </a-row>
          </template>
        </a-tree>
      </a-form>
    </div>
    <template #footer>
      <a-button @click="modal.open = false">取消</a-button>
      <a-button key="submit" type="primary" @click="confirm">确定</a-button>
    </template>
  </a-modal>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import IconFont from '@/components/IconFont/index.vue'
import store from '@/store'
import _ from 'lodash'

const modal = reactive({
  title: '题目关联',
  open: false
})

const modelForm = ref(null)

const showCondition = ref({
  operator: 'AND',
  show: true,
  top: true,
  conditions: [
    {
      key: '0-0',
      namse: ['conditions', 0],
      id: '',
      operator: '===',
      value: ''
    }
  ]
})

const expandedKeys = ref([])

const init = (item) => {
  modelForm.value?.clearValidate()

  if (item) {
    if (!item.hasOwnProperty('show')) {
      item['show'] = true
    }
    setNames(item.conditions)
    showCondition.value = item
    showCondition.value['top'] = true
  } else {
    showCondition.value = {
      operator: 'AND',
      show: true,
      top: true,
      conditions: [
        {
          key: '0-0',
          names: ['conditions', 0],
          id: '',
          operator: '===',
          value: ''
        }
      ]
    }
    expandedKeys.value = ['0-0']
  }

  modal.open = true
}

// const showConditionObj = ref({})
const handleMenuClick = (e, c) => {
  console.log(e, c)
  c.operator = e.key
  if (e.key === 'AND' || e.key === 'OR') {
    c['conditions'] = [
      {
        key: `${c.key}-0`,
        names: [...c.names, 'conditions', 0],
        id: '',
        operator: '===',
        value: ''
      }
    ]
  } else {
    c['conditions'] = []
  }
  setNames(showCondition.value.conditions)
  console.log(showCondition.value)
}

const setNames_loop = (list, p, k, keys) => {
  list.map((v, i) => {
    console.log(p)
    v['names'] = [...p, 'conditions', i]
    v['key'] = `${k}-${i}`
    keys.push(v.key)
    if (Object.prototype.hasOwnProperty.call(v, 'conditions') && v.conditions.length) {
      setNames_loop(v.conditions, v.names, v.key, keys)
    }
  })
}

const setNames = (list) => {
  expandedKeys.value = []
  const keys = []

  list.map((v, i) => {
    v['names'] = ['conditions', i]
    v['key'] = `0-${i}`
    keys.push(v.key)
    if (Object.prototype.hasOwnProperty.call(v, 'conditions') && v.conditions.length) {
      setNames_loop(v.conditions, v.names, v.key, keys)
    }
  })
  console.log(keys)
  expandedKeys.value = keys
}

const conditionsAdd = (names) => {
  const list = names.reduce((pre, cur, index) => {
    if (index < names.length - 1) {
      return pre[cur]
    } else {
      return pre
    }
  }, showCondition.value)
  console.log(list)
  list.push({
    id: '',
    operator: '===',
    value: ''
  })
  setNames(showCondition.value.conditions)
}

const conditionsDel = (i, names) => {
  const list = names.reduce((pre, cur, index) => {
    if (index < names.length - 1) {
      return pre[cur]
    } else {
      return pre
    }
  }, showCondition.value)
  console.log(list)
  list.splice(i, 1)
  setNames(showCondition.value.conditions)
}

const conditionsChange = (type, c) => {
  if (type === '输入') {
    c.operator = '填写完成'
    c.value = ''
  } else if (type === '搜索输入') {
    c.operator = '填写完成'
    c.value = ''
  } else {
    c.operator = '==='
    c.value = ''
  }
}

const operatorChange = (e, c) => {
  console.log(e)
  if (e === '填写完成') {
    c.value = ''
  }
}

const simpleCheck = ref(true)

const simple = (list) => {
  list.map((v, i) => {
    if (Object.prototype.hasOwnProperty.call(v, 'conditions')) {
      if (v.conditions.length === 1) {
        simple(list[i].conditions)
        if (!v.top) {
          list[i] = v.conditions[0]
        }
      } else if (v.conditions.every((u) => u.operator === v.operator)) {
        simple(list[i].conditions)
        list[i].conditions = v.conditions.reduce((pre, cur) => {
          return [...pre, ...cur.conditions]
        }, [])
      }
    }
  })
}

const clearCondition = (list) => {
  list.map((v) => {
    delete v.names
    delete v.key
    if (Object.prototype.hasOwnProperty.call(v, 'conditions') && v.conditions.length) {
      clearCondition(v.conditions)
    } else if (Object.prototype.hasOwnProperty.call(v, 'conditions') && !v.conditions.length) {
      delete v.conditions
    }
  })
}

const confirm = () => {
  modelForm.value.validate().then(() => {
    const d = _.cloneDeep(showCondition.value)
    clearCondition(d.conditions)
    if (simpleCheck.value) {
      simple(d.conditions)
      delete d.top
      // if (d.conditions.length === 1) {
      //   d.operator = d.conditions[0].operator
      //   d.conditions = d.conditions[0].conditions
      // }
    }
    console.log(d)

    emit('onConfirm', d)

    modal.open = false
  })
}

const props = defineProps({
  formData: Object,
  showConditionObj: Object
})

const emit = defineEmits(['onConfirm'])

defineExpose({
  init
})
</script>

<style lang="less" scoped>
.modal-content {
  ::v-deep(.ant-tree-treenode) {
    width: 100%;
    .ant-tree-node-content-wrapper {
      width: 100%;
    }
  }
  .row {
    display: flex;
    justify-content: space-between;
  }
}
.ft {
  height: 32px;
  flex: 1;
  display: flex;
  flex-direction: row-reverse;
}
.icon-plus,
.icon-del {
  font-size: 16px;
}
.icon-plus {
  color: #165dff;
}
.icon-del {
  color: #f53f3f;
}
</style>
